<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas{
				display: block;
				margin: 0 auto;
				box-shadow: 0 0 10px rgba(0,0,0,0.5);
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<script src="../libs/utils.js"></script>
		<script type="text/javascript">
			class Ball {
				constructor(props) {
					this.x = 0;
					this.y = 0;
					this.r = 25;
					this.scaleX = 1;
					this.scaleY = 1;
					this.fillStyle = 'rgba(65,168,99,1)';
					this.strokeStyle = 'rgba(0,0,0,0)';
					Object.assign(this,props)
					return this
				}
				render(ctx){
					var {x,y,r,fillStyle,strokeStyle,scaleX,scaleY} = this
					// 保存绘图环境
					ctx.save()
					// 将画布坐标移动到x，y
					ctx.translate(x,y)
					ctx.scale(scaleX,scaleY) 
					ctx.fillStyle = fillStyle;
					ctx.strokeStyle = strokeStyle;
					ctx.beginPath()
					ctx.arc(0,0,r,0,2*Math.PI,false)
					ctx.fill()
					ctx.stroke()
					// 恢复绘图环境
					ctx.restore()
					return this
				}
			}
		</script>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas')
			var ctx = canvas.getContext('2d');
			
			var w = canvas.width = 500;
			var h = canvas.height = 300
			
			var angle = 0;
			// 初始缩放值
			var initScale = 1;
			// 摆幅最大0.5的变化
			var swing = 0.5;
			// 实例化小球
			var ball = new Ball({x:w/2,y:h/2,scaleX:initScale,scaleY:initScale}).render(ctx);
			// 运动
			(function move(){
				window.requestAnimationFrame(move)
				// 清空画布
				ctx.clearRect(0,0,w,h)
				// 设置小球的缩放大小:初始值+摆幅*(1~-1)
				ball.scaleX = ball.scaleY = initScale + Math.sin(angle) * swing;
				// 弧度每次增加0.02
				angle +=0.02;
				// 并且%上2Π，Math.sin(angle)的值就会0->1->0->-1的值进行切换
				angle %=2*Math.PI;
				ball.render(ctx)
			})()
		</script>
	</body>
</html>
